import os
import sys
import django

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.extend([BASE_DIR, ])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")
django.setup()
from apps.sales_man.models import SalesMan
from core.tools.encryption import md5
from django.db.models import F


def export_data(result_json):
    import xlwt
    book = xlwt.Workbook()  # 创建excel对象
    # 写表头
    leader_row = 0
    sheet1 = book.add_sheet('account')  # 添加一个表
    # 写表头
    header_line = ["账号", "密码", "类型", "链接"]
    for header in header_line:
        sheet1.write(0, leader_row, header)
        leader_row += 1
    row1 = 1
    for i in result_json:
        account = i.get("account")
        sheet1.write(row1, 0, account)
        sheet1.write(row1, 1, i.get("password"))
        sheet1.write(row1, 2, 1)  # 信用卡
        sheet1.write(row1 + 1, 2, 2)  # 信用贷
        xyk = "https://oss.kalaibao.com/developer/index.html#/?account=%s&type=1" % account
        xyd = "https://oss.kalaibao.com/developer/index.html#/?account=%s&type=2" % account
        sheet1.write(row1, 3, xyk)  # 信用卡链接
        sheet1.write(row1 + 1, 3, xyd)  # 信用贷链接
        row1 += 2
    book.save("accounts.xls")


def create_account(channel_code, people_num, channel):
    import time
    import random
    data_json = []
    leader = SalesMan.objects.get(account=channel_code)
    for i in range(people_num):
        data = dict()
        v = random.randint(0, 100000)
        s = float(v) / 100000
        time.sleep(s)
        account = str(time.time()).replace(".", "")
        base_account = account[10:]
        account = channel_code + base_account
        base_password = int(base_account) + v
        base_password = str(base_password)[-8:]
        salesman, created = SalesMan.objects.get_or_create(
            account=account,
        )
        if created:
            password = md5(base_password)
            password = md5(password)
            salesman.password = password
            salesman.channel_id = channel
            salesman.leader = leader
            salesman.show_alert = False
            salesman.save()
            data["account"] = account
            data["password"] = base_password
            data_json.append(data)
        else:
            continue
    leader.num = F("num") + people_num
    leader.save()
    export_data(data_json)


if __name__ == '__main__':
    channel_code = "c01twj"
    people_num = 10
    channel = 22
    create_account(channel_code, people_num, channel)
